package com.bizmerce.rnd.oms.criterion.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.bizmerce.rnd.oms.criterion.service.CriterionService;
import com.bizmerce.rnd.oms.criterion.vo.AgreeVO;
import com.bizmerce.rnd.oms.criterion.vo.ConfirmDocIssueVO;
import com.bizmerce.rnd.oms.criterion.vo.SendbackVO;
import com.bizmerce.rnd.oms.criterion.vo.SupplOrigInfoVO;
import com.bizmerce.rnd.oms.criterion.vo.SupplPartNoVO;
import com.bizmerce.rnd.oms.util.ParamMap;

import egovframework.rte.fdl.cmmn.AbstractServiceImpl;

@Service("criterionService")
public class CriterionServiceImpl extends AbstractServiceImpl implements CriterionService {

    Log log = LogFactory.getLog(CriterionServiceImpl.class);
    
	@Resource(name= "criterionDAO")
	CriterionDAO criterionDAO;	
	
	/**
	 * 미결부품을 조회.
	 */
	public List <SupplPartNoVO> selectUnsettledParts(ParamMap param) {
	    
	    List <SupplPartNoVO> list = criterionDAO.selectUnsettledParts(param);
	    
	    return list;
	}
	
	/**
	 * 적용 협정 조회
	 * @param param
	 * @return
	 */
	public List<AgreeVO> selectApplyAgree() {        
        return criterionDAO.selectApplyAgree();   
    }
	public String selectApplyAgreeNames() {
	    List <AgreeVO> result = this.selectApplyAgree();        
        List <String> agreeList = new ArrayList <String>();
        for (AgreeVO vo : result) {
            agreeList.add(vo.getAgreeNm());
        }
        return StringUtils.join(agreeList.iterator(),"/");
	}
	
	/**
	 * 미결부품들 내용을 저장.
	 */
    public void saveUnsettledParts(ParamMap param) {

        String userId       = param.getString("userId");
        String cmpyCd       = param.getString("cmpyCd");
        String [] partNo    = param.getArray("partNo");
        String [] supplHscd = param.getArray("supplHscd");
        String [] retnrea   = param.getArray("retnrea", " ");
        
        int updateCount = 0;
        for (int cnt=0 ; cnt < partNo.length ; cnt++) {    
            updateCount += criterionDAO.saveUnsettledParts(userId, cmpyCd, partNo[cnt], supplHscd[cnt], retnrea[cnt]);
        }
        
        if (log.isDebugEnabled()) {
            log.debug("미결부품 저장 실행 건수:"+partNo.length);
            log.debug("미결부품 저장 완료 건수:"+updateCount);
        }
    }

    /**
     * 미결부품을 반송.
     */
    public void sendbackUnsettledParts(ParamMap param) {
        
        String userId      = param.getString("userId");
        String cmpyCd      = param.getString("cmpyCd");
        String [] checkIdx = param.getArray("checkIdx");
        String [] partNo   = param.getArray("partNo");
        String [] retnrea  = param.getArray("retnrea");
        
        int updateCount = 0;
        for (String check : checkIdx) {    
            int idx = Integer.parseInt(check);
            updateCount += criterionDAO.sendbackUnsettledParts(userId, cmpyCd, partNo[idx], retnrea[idx], "B"); // 상태코드-반송:B 
        }
        
        if (log.isDebugEnabled()) {
            log.debug("미결부품 반송 실행 건수:"+checkIdx.length);
            log.debug("미결부품 저장 완료 건수:"+updateCount);            
        }
    }
    
    /**
     * 확인서작성-조회 (확인서작성이 가능한 부품 조회)
     */
    public List <SupplPartNoVO> selectConfirmParts(ParamMap param) {
        return criterionDAO.selectConfirmParts(param);
    }

    /**
     * 확인서작성(제출화면)-조회 
     */
    public List <SupplPartNoVO> selectConfirmPartsFTA(ParamMap param) {
        if (param.getInt("ALL") == 1) 
            return criterionDAO.selectConfirmPartsFTAAll(param);
        else {
            return criterionDAO.selectConfirmPartsFTA(param);  
        }            
    }
    
    /**
     * 확인서작성(제출화면)-제출
     */
    public void insertConfirmPartsFTA(ParamMap param) {
        
        String userId          = param.getString("userId");      
        String userDegree      = param.getString("userDegree");     
        
        String cmpyCd          = param.getString("cmpyCd");      // 업체코드
        String [] partNo       = param.getArray("partNo");       // 부품
        String [] agreeCd      = param.getArray("agreeCd");      // 협정코드
        String [] rule         = param.getArray("rule");         // 결정기준
        String [] vaRate       = param.getArray("vaRate");       // 부가가치비율
        String [] origSatiYn   = param.getArray("origSatiYn");   // 충족여부
        String [] orig         = param.getArray("orig");         // 원산지
        String [] orgCondition = param.getArray("orgCondition"); // 원산지조건
        
        String coIssno = criterionDAO.selectNewCoIssno(cmpyCd);    // 발급번호 생성
        
        // 업체 등록
        // TODO APPL_DIVI 처리구분값 파악해서 넣을것
        criterionDAO.insertConfirmPartsFTA2(userId, userDegree, cmpyCd, coIssno);
        
        String previousPartNo = "";        
        for (int cnt=0 ; cnt < partNo.length ; cnt++) {  
            
            if ( ! previousPartNo.equals(partNo[cnt])) {
                criterionDAO.updateSupplPartNo(userId, cmpyCd, partNo[cnt], "D"); // 상태코드 확인서발급으로 업데이트
                previousPartNo = partNo[cnt];
            }
            
            // 부품별 등록
            criterionDAO.insertConfirmPartsFTA1(cmpyCd, 
                                                partNo[cnt], 
                                                coIssno, 
                                                agreeCd[cnt], 
                                                rule[cnt], 
                                                vaRate[cnt], 
                                                origSatiYn[cnt], 
                                                orig[cnt], 
                                                orgCondition[cnt]);
            
        }
    }
    
    /**
     * 원산지확인서발급관리-PART_NO로 조회.
     */
    public List <SupplOrigInfoVO> selectConfirmDocIssue1(ParamMap param) {
        return criterionDAO.selectConfirmDocIssue1(param);
    }
    
    /**
     * 원산지확인서발급관리-확인서번호로 조회.
     */
    public List <ConfirmDocIssueVO> selectConfirmDocIssue2(ParamMap param) {
        return criterionDAO.selectConfirmDocIssue2(param);
    }
    
    /**
     * 반송관리-조회
     */
    public List <SendbackVO> selectSendback(ParamMap param) {
        return criterionDAO.selectSendback(param);
    }
    
    /**
     * 반송관리-반송승인
     */
    public void approveSendBack(ParamMap param) {
        String userId = param.getString("userId"); // 수정자ID
        
        String [] checkIdx = param.getArray("checkIdx"); // checked item ==> partNo@cmpyCd
        
        for (String items : checkIdx) {
            String partNo = StringUtils.split(items, "@")[0];
            String cmpyCd = StringUtils.split(items, "@")[1];
            
            criterionDAO.updateSupplPartNo(userId, cmpyCd, partNo, "S");   
        }
    }

    /**
     * 반송관리-재요청
     */
    public void requestSendBack(ParamMap param) {
        String userId = param.getString("userId"); // 수정자ID
        
        String [] checkIdx = param.getArray("checkIdx"); // checked item ==> partNo@cmpyCd
        
        for (String items : checkIdx) {
            String partNo = StringUtils.split(items, "@")[0];
            String cmpyCd = StringUtils.split(items, "@")[1];
            
            criterionDAO.sendbackUnsettledParts(userId, cmpyCd, partNo, "", "B"); // 상태코드-반송:B   
        }        
    }
}
